import star from '../../assets/star.png'
import Phaser from 'phaser'
import dude from '../../assets/dude.png'

export default class CameraScene extends Phaser.Scene {

    constructor() {
        super('cameraScene')
    }

    preload() {
        this.load.image('star', star);
        this.load.spritesheet('dude', dude, { 
            frameWidth: 32, 
            frameHeight: 48 
        });
    }

    create() {
        // 1. 先创建一个很大的游戏世界（2000x2000）
        this.physics.world.setBounds(0, 0, 2000, 2000);
        
        // 2. 在世界的不同位置创建一些参考物（星星）
        this.createReferencePoints();
        
        // 3. 创建玩家
        this.player = this.physics.add.sprite(300, 400, 'dude');
        this.player.setCollideWorldBounds(true);
        this.player.body.setGravityY(300);
        this.player.setBounce(0.3);
        
        // 创建动画
        this.anims.create({
            key: "dude_anim",
            frames: this.anims.generateFrameNumbers('dude', { start: 1, end: 8 }),
            frameRate: 10,
            repeat: -1
        });
        this.player.play('dude_anim');

        // 4. 创建地面和平台
        this.createPlatforms();
        
        // 5. 设置相机边界（覆盖整个大世界）
        this.cameras.main.setBounds(0, 0, 2000, 2000);
        this.cameras.main.setBackgroundColor(0x87ceeb);

        // 6. 添加控制
        this.cursors = this.input.keyboard.createCursorKeys();
        
        // 7. 添加调试信息
        this.debugText = this.add.text(10, 10, '', { 
            fontSize: '16px', 
            fill: '#fff' 
        }).setScrollFactor(0); // 设置scrollFactor为0，让文字固定在屏幕上
        
        // 8. 添加切换相机模式的按键
        this.setupCameraControls();
        
        // 9. 默认启用相机跟随
        this.cameraFollowEnabled = true;
        this.cameras.main.startFollow(this.player, {
            lerp: { x: 0.05, y: 0.05 },
            roundPixels: true
        });
    }

    createReferencePoints() {
        // 在世界各处创建参考点，帮助你理解相机移动
        const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff];
        
        for (let i = 0; i < 20; i++) {
            const x = Phaser.Math.Between(100, 1900);
            const y = Phaser.Math.Between(100, 1900);
            const color = colors[i % colors.length];
            
            // 创建参考点
            const point = this.add.rectangle(x, y, 30, 30, color);
            const text = this.add.text(x, y + 25, `(${x},${y})`, {
                fontSize: '12px',
                fill: '#000'
            });
            
            // 创建星星
            this.add.image(x + 100, y, 'star').setScale(0.3);
        }
    }

    createPlatforms() {
        // 创建多个平台
        const platforms = [
            { x: 400, y: 580, width: 800, height: 40 }, // 主地面
            { x: 200, y: 450, width: 200, height: 20 },
            { x: 600, y: 350, width: 200, height: 20 },
            { x: 1000, y: 500, width: 300, height: 20 },
            { x: 1500, y: 300, width: 400, height: 20 }
        ];
        
        platforms.forEach(platform => {
            const ground = this.add.rectangle(platform.x, platform.y, platform.width, platform.height, 0x00aa00);
            this.physics.add.existing(ground, true);
            // ground.body.setAllowGravity(false);
            this.physics.add.collider(this.player, ground);
        });
    }

    setupCameraControls() {
        // 空格键：切换相机跟随模式
        this.spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
        
        // Z键：放大
        this.zKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Z);
        
        // X键：缩小
        this.xKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.X);
        
        // C键：重置缩放
        this.cKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.C);
        
        // R键：移动到随机位置
        this.rKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.R);
    }

    update(time, delta) {
        // 更新调试信息
        this.updateDebugInfo();
        
        // 处理玩家移动
        this.handlePlayerMovement();
        
        // 处理相机控制
        this.handleCameraControls();
    }

    updateDebugInfo() {
        const camera = this.cameras.main;
        this.debugText.setText([
            '=== 相机系统演示 ===',
            `玩家位置: (${Math.round(this.player.x)}, ${Math.round(this.player.y)})`,
            `相机位置: (${Math.round(camera.scrollX)}, ${Math.round(camera.scrollY)})`,
            `相机缩放: ${camera.zoom.toFixed(2)}`,
            `相机跟随: ${this.cameraFollowEnabled ? '开启' : '关闭'}`,
            '',
            '=== 控制说明 ===',
            '方向键: 移动玩家',
            '空格键: 切换相机跟随',
            'Z键: 相机放大',
            'X键: 相机缩小', 
            'C键: 重置缩放',
            'R键: 传送到随机位置'
        ].join('\n'));
    }

    handlePlayerMovement() {
        // 玩家移动逻辑
        if (this.cursors.left.isDown) {
            this.player.setVelocityX(-160);
            this.player.setFlipX(true);
        } else if (this.cursors.right.isDown) {
            this.player.setVelocityX(160);
            this.player.setFlipX(false);
        } else {
            this.player.setVelocityX(0);
        }
        
        if (this.cursors.up.isDown && this.player.body.touching.down) {
            this.player.setVelocityY(-400);
        }
    }

    handleCameraControls() {
        // 切换相机跟随模式
        if (Phaser.Input.Keyboard.JustDown(this.spaceKey)) {
            this.cameraFollowEnabled = !this.cameraFollowEnabled;
            
            if (this.cameraFollowEnabled) {
                this.cameras.main.startFollow(this.player, {
                    lerp: { x: 0.05, y: 0.05 },
                    roundPixels: true
                });
            } else {
                this.cameras.main.stopFollow();
            }
        }
        
        // 相机缩放控制
        if (Phaser.Input.Keyboard.JustDown(this.zKey)) {
            this.cameras.main.zoomTo(2, 300); // 放大到2倍
        }
        
        if (Phaser.Input.Keyboard.JustDown(this.xKey)) {
            this.cameras.main.zoomTo(0.5, 300); // 缩小到0.5倍
        }
        
        if (Phaser.Input.Keyboard.JustDown(this.cKey)) {
            this.cameras.main.zoomTo(1, 300); // 重置缩放
        }
        
        // 随机传送
        if (Phaser.Input.Keyboard.JustDown(this.rKey)) {
            const x = Phaser.Math.Between(100, 1900);
            const y = Phaser.Math.Between(100, 1900);
            this.player.setPosition(x, y);
            
            // 如果相机没有跟随，让相机也移动到该位置
            if (!this.cameraFollowEnabled) {
                this.cameras.main.pan(x, y, 1000);
            }
        }
    }
}